﻿using System;
using System.Collections.Generic;
using System.IO;

namespace remove_file.Utils
{
    public class FileUtils
    {

        public struct RemoveFileError
        {
            public Exception error;
        }

        public class RemoveFileErrorList : List<Exception>
        {

            public override string ToString() 
            {
                string result = "";
                foreach (var error in this)
                {
                    result += error.Message + "\n";
                }
                return result;
            }
        }

        public static bool RemoveDirectory(string dirPath, RemoveFileErrorList errorList) 
        {
            if (!Directory.Exists(dirPath))
            {
                errorList.Add(new DirectoryNotFoundException("为能找到文件夹\"" + dirPath + "\"。"));
                return true;
            }

            bool result = true;

            string[] dirNames = Directory.GetDirectories(dirPath);
            string[] fileNames = Directory.GetFiles(dirPath);

            foreach (string fileName in fileNames)
            {
                try
                {
                    File.Delete(fileName);
                }
                catch (Exception error)
                {
                    errorList.Add(error);
                    result = false;
                }
            }

            foreach (string dirName in dirNames)
            {
                bool childResult = RemoveDirectory(dirName, errorList);
                if (!childResult) 
                { 
                    result = false;
                }
            }

            if (result)
            {
                try
                {
                    Directory.Delete(dirPath);
                }
                catch (Exception error)
                {
                    errorList.Add(error);
                }
            }
            
            return result;
        }
    }
}
